import React, { useContext, useState, useEffect, useRef } from 'react';
import { Table, Input, Button, Popconfirm, Form, Divider } from 'antd';

import { putLocalStorage, getLocalStorage } from '@/utils/localStorage';

import { connect, FormattedMessage, useIntl } from 'umi';

const EditableContext = React.createContext();

const EditableRow = ({ index, ...props }) => {
    const [form] = Form.useForm();
    return (
        <Form form={form} component={false}>
            <EditableContext.Provider value={form}>
                <tr {...props} />
            </EditableContext.Provider>
        </Form>
    );
};

const EditableCell = ({
    title,
    editable,
    children,
    dataIndex,
    record,
    handleSave,
    ...restProps
}) => {
    const [editing, setEditing] = useState(false);
    const [editingValue, setEditingValue] = useState('');

    const inputRef = useRef();
    const form = useContext(EditableContext);
    useEffect(() => {
        if (editing) {
            if (inputRef.current) {
                inputRef.current.focus();
                // if (editingValue != undefined && editingValue != '') {
                //     inputRef.current.setValue(editingValue);
                // }
            }
        }
    }, [editing]);


    const toggleEdit = () => {
        setEditingValue('');
        if ('delete' == event.target.id) {
            return;
        }

        setEditingValue(event.target.textContent);
        setEditing(!editing);
    };

    const save = async e => {
        try {
            const values = await form.validateFields();
            toggleEdit();

            handleSave({ ...record, ...values });
        } catch (errInfo) {
            console.log('Save failed:', errInfo);
        }
    };

    let childNode = children;

    if (editable) {
        childNode = editing ? (
            <Form.Item
                style={{
                    margin: 0,
                }}
                name={dataIndex}
                initialValue={editingValue}
                rules={[
                    {
                        required: true,
                        message: `${title} is required.`,
                    },
                ]}
            >
                <Input ref={inputRef} onPressEnter={save} onBlur={save} />
            </Form.Item>
        ) : (
                <div
                    className="editable-cell-value-wrap"
                    style={{
                        paddingRight: 24,
                    }}
                // onClick={toggleEdit}
                >
                    {children}
                </div>
            );
    }

    return <td onClick={toggleEdit} {...restProps}>{childNode}</td>;
};

class EditableTable extends React.Component {
    constructor(props) {
        super(props);
        this.columns = [
            {
                title: '参数名称',
                dataIndex: 'pname',
                width: '20%',
                editable: true,
                ellipsis: true,
            },
            {
                title: '参数值',
                dataIndex: 'pvalue',
                editable: true,
                width: '20%',
                ellipsis: true,
            },
            {
                title: '参数说明',
                dataIndex: 'pdesc',
                editable: true,
                width: '35%',
                ellipsis: true,
            },
            {
                title: '操作',
                align: 'center',
                dataIndex: 'operation',
                render: (text, record) =>
                    this.state.dataSource.length >= 1 ? (
                        <div>
                            <Popconfirm title="确认删除吗?" onConfirm={() => this.handleDelete(record.key)}>
                                <a id='delete'>删除</a>
                            </Popconfirm>

                        </div>
                    ) : null,
            },
        ];
        this.state = {
            dataSource: this.getLoalValues().data,
            count: this.getLoalValues().size,
        };
    }
    getLoalValues = () => {
        var dataSource = getLocalStorage('dx_swagger_ui_cache');
        if (dataSource != undefined) {
            var data = JSON.parse(dataSource);
            var size = data.length;
            return { data: data, size: size };
        } else {
            return { data: [], size: 0 };
        }
        // var values = [
        //     {
        //         key: '0',
        //         pname: 'Edward King 0',
        //         pvalue: '32',
        //         pdesc: 'London, Park Lane no. 0',
        //     },
        // ];
        // return values;
    }
    handleDelete = key => {
        const dataSource = [...this.state.dataSource];
        var dataSourcex = dataSource.filter(item => item.key !== key);
        this.setState({
            dataSource: dataSourcex,
        });

        putLocalStorage('dx_swagger_ui_cache', JSON.stringify(dataSourcex));
    };

    handleAdd = () => {
        const { count, dataSource } = this.state;
        var ncount = count + 1;
        const newData = {
            key: ncount,
            pname: ``,
            pvalue: ``,
            pdesc: ``,
        };
        this.setState({
            dataSource: [...dataSource, newData],
            count: ncount,
        });
    };

    handleSave = row => {
        const newData = [...this.state.dataSource];
        const index = newData.findIndex(item => row.key === item.key);
        const item = newData[index];
        newData.splice(index, 1, { ...item, ...row });
        this.setState({
            dataSource: newData,
        });
    };
    handleSave2 = () => {
        const { count, dataSource } = this.state;

        putLocalStorage('dx_swagger_ui_cache', JSON.stringify(dataSource));
    };
    render() {
        const { dataSource } = this.state;
        const components = {
            body: {
                row: EditableRow,
                cell: EditableCell,
            },
        };
        const columns = this.columns.map(col => {
            if (!col.editable) {
                return col;
            }

            return {
                ...col,
                onCell: record => ({
                    record,
                    editable: col.editable,
                    dataIndex: col.dataIndex,
                    title: col.title,
                    handleSave: this.handleSave,
                }),
            };
        });
        return (
            <div>
                <Button
                    onClick={this.handleAdd}
                    type="primary"
                    style={{
                        marginBottom: 16,
                    }}
                >
                    新增
                </Button>
                &nbsp;
                <Button
                    onClick={this.handleSave2}
                    type="primary"
                    style={{
                        marginBottom: 16,
                    }}
                >
                    保存
                </Button>
                <Table
                    components={components}
                    rowClassName={() => 'editable-row'}
                    size={"small"}
                    pagination={false}
                    bordered
                    dataSource={dataSource}
                    columns={columns}
                />
            </div>
        );
    }
}
export default EditableTable